package com.lw.sbdemo2.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.lw.sbdemo2.common.exception.ApiException;
import com.lw.sbdemo2.common.exception.ResponseCodeEnum;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.imageio.ImageIO;

/**
 * <p>标题: 二维码生成工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2017</p>
 * <p>公司: 智业软件</p>
 *
 * @author: linqunyuan
 * @createTime 2018/4/9
 */
public class QrcodeUtil {

    /**
     * 二维码方块颜色默认是黑色
     */
    private static final int QRCOLOR = 0xFF000000;

    /**
     * 背景颜色
     */
    private static final int BGWHITE = 0xFFFFFFFF;

    /**
     * 二维码宽
     */
    private static final int WIDTH = 300;

    /**
     * 二维码高
     */
    private static final int HEIGHT = 300;

    /**
     * 用于设置QR二维码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            //设置QR二维码的纠错级别（H为最高级别）具体级别信息
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            //设置编码方式
            put(EncodeHintType.CHARACTER_SET, "utf-8");
            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * 生成带LOGO二维码图片
     *
     * @param logoFile
     * @param codeFile
     * @param content
     * @param note
     */
    public static void drawLogoQRCode(File logoFile, File codeFile, String content, String note) {
        try {

            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }

            int width = image.getWidth();
            int height = image.getHeight();
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片
                g.drawImage(logo, width * 2 / 5, height * 2 / 5,
                        width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }

            // 自定义文本描述
            if (ValidUtil.isNotEmpty(note)) {

                // 新的图片，把带logo的二维码下面加上文字
                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // 画二维码到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 画文字到新的面板
                outg.setColor(Color.BLACK);
                // 字体、字型、字号
                outg.setFont(new Font("楷体", Font.BOLD, 30));
                int strWidth = outg.getFontMetrics().stringWidth(note);
                //长度过长就截取前面部分,过长换行
                if (strWidth > 399) {
                    String note1 = note.substring(0, note.length() / 2);
                    String note2 = note.substring(note.length() / 2, note.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                    outg.drawString(note1, 200 - strWidth1 / 2, height +
                            (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    // 字体、字型、字号
                    outg2.setFont(new Font("宋体", Font.BOLD, 30));
                    outg2.drawString(note2, 200 - strWidth2 / 2, outImage.getHeight() +
                            (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } else {
                    // 画文字
                    outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12);
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }

            image.flush();

            if (codeFile.exists()) {
                // 文件已经存在，输出文件的相关信息
                ImageIO.write(image, "png", codeFile);
            } else {
                //  先创建文件所在的目录
                codeFile.getParentFile().mkdirs();
                try {
                    // 创建新文件
                    codeFile.createNewFile();
                    ImageIO.write(image, "png", codeFile);
                } catch (IOException e) {
                    throw new ApiException(ResponseCodeEnum.EX_RESULT, "创建新文件时出现了错误");
                }
            }


        } catch (Exception e) {
            throw new ApiException(ResponseCodeEnum.EX_RESULT, "创建二维码失败");
        }
    }

    public static String readQrcode(String cardNo) throws Exception {

        MultiFormatReader multiFormatReader = new MultiFormatReader();
        String path = QrcodeUtil.class.getClassLoader().getResource("").getPath();
        File file = new File(path + "/static/qrcode/" + cardNo + ".png");
        BufferedImage image = ImageIO.read(file);

        //定义二维码参数
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        //获取读取二维码结果
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Result result = multiFormatReader.decode(binaryBitmap, hints);
        return result.getText();
    }
}
